'use strict';

import SyncRequest from 'sync-request';
import X2JS from 'x2js';
import {
  cache
} from "./CacheFile";

let fs = require('fs');
let x2js = new X2JS();

Array.prototype.contains = function (obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

class SmzdmRss {
  constructor(rss = 'feed') {
    this._debug = false;
    this._error = null;
    this._load = false;
    this._cacheTime = 60 * 15;
    this._rss = '';
    this._items = [];
    this._rss_sources = [{
      'name': 'feed',
      'tags': ['feed', '优惠精选'],
      'url': 'http://feed.smzdm.com/'
    }, {
      'name': 'haitao',
      'tags': ['haitao', '海淘专区'],
      'url': 'http://haitao.smzdm.com/feed'
    }, {
      'name': 'post',
      'tags': ['post', '原创频道'],
      'url': 'http://post.smzdm.com/feed'
    }, {
      'name': 'faxian',
      'tags': ['faxian', '发现频道'],
      'url': 'http://faxian.smzdm.com/feed'
    }, {
      'name': 'news',
      'tags': ['news', '资讯专区'],
      'url': 'http://news.smzdm.com/feed'
    }];

    this._rss_sources.forEach((item, index) => {
      this._rss_sources[index]['qcloud'] = '	http://spider-1251008422.cossh.myqcloud.com/smzdm/rss/' + item.name + '_titles.json';
    });

    let rssName = this.getRssAttr(rss, 'name');
    if (this.getRssAttr(rss)) {
      this._rss = rssName;
    } else {
      this._error = '该频道目前尚未收录。';
    }
  }

  getRssAttr(rss, field = 'url') {
    let res = '';
    this._rss_sources.forEach((item) => {
      if (item.tags.contains(rss)) {
        res = item[field];
      }
    });
    return res;
  }

  parseItems(content) {
    let jsonObj = x2js.xml2js(content);
    this._items = jsonObj.rss.channel.item;
    return jsonObj.rss.channel.item
  }

  fetchOnline(cacheName, timeout = 15000) {
    let content = '';
    if (this._debug) {
      content = fs.readFileSync('./tests/feed.xml', 'utf-8');
    } else {
      let response = SyncRequest('get', this.getRssAttr(this._rss), {
        timeout: timeout
      });
      if (response && response.statusCode === 200) {
        content = response.getBody('utf8');
      } else {
        this._error = '无法获取服务端数据';
      }
    }
    return this.parseItems(content);
  }

  fetchQCloud(cacheName) {
    let content = '';
    console.log(this.getRssAttr(this._rss, 'qcloud'));
    let response = SyncRequest('get', this.getRssAttr(this._rss, 'qcloud'), {
      timeout: 1500
    });
    if (response && response.statusCode === 200) {
      content = response.getBody('utf8');
    } else {
      this._error = '无法获取服务端数据';
    }
    this._items = JSON.parse(content);
    return this._items;
  }

  fetch() {
    let self = this;
    let content = cache.get(self._rss);
    if (content) {
      self._items = content;
    }
    // if (!content) {
    //   console.log('[Fetch]', 'QCloud');
    //   content = self.fetchQCloud(self._rss);
    // }
    if (!content) {
      console.log('[Fetch]', 'Online');
      content = self.fetchOnline(self._rss);
    }
    return content;
  }

  load() {
    if (this._error) {
      return this._error;
    } else {
      let content = this.fetch();
    }
  }

  getPageNo(page, page_offset, direction) {
    if (direction == 'prev') {
      page -= page_offset;
    } else {
      page += page_offset;
    }
    return page;
  }


  pager(page = 1, size = 5) {
    if (this._error) {
      return this._error;
    } else {
      let pages = 1;
      let items = [];
      let offset = (page - 1) * size;
      if (this._items && this._items.length > 0) {
        pages = Math.ceil(this._items.length / size);
      }
      if (page > pages) page = pages;
      this._items.forEach((item, index) => {
        if (index >= offset && index < (page * size)) {
          items.push(item.title);
        }
      });
      return {
        page,
        pages,
        size,
        items
      };
    }
  }

  fetchAll(name, level = 'titles') {
    console.log('[Fetch All]', 'starting');
    let self = this;
    let contents = [];
    self._rss_sources.forEach((rss) => {
      if (name && name !== rss.name) {
        return;
      }
      console.log('[Fetch All]', rss.name);
      let content = self.fetchOnline(rss.name, 1000 * 60);
      if (content) {
        switch (level) {
          case 'titles':
            let items = [];
            content.forEach((item, index) => {
              items.push({
                title: item.title
              });
            });
            content = items;
            break;
          default:
            content = content;
            break;
        }
        // self.createCache(rss.name, content, self.fetchAll);
        contents.push({
          'name': rss.name,
          'content': content
        })
      }
    });
    console.log('[Fetch All]', 'done');
    return contents;
  }
}

export default SmzdmRss;
export {
  SmzdmRss
};
